#
# LsL::UpLoad.pm
#
# Copyright (C) 2004 Albacore Technology, LLC All Rights Reserved
#
# $Id: $
#

package LsL::UpLoad;

use strict;
use Apache2::Const -compile => qw(REDIRECT DECLINED FORBIDDEN OK);

use vars qw( $VERSION @ISA @EXPORT @EXPORT_OK $BASE_PATH $BASE_DIR );
use Exporter;
use IO::File;

#
# public (exported) variables
#
@EXPORT_OK = qw();
@ISA       = qw(Exporter);
@EXPORT    = qw();
$VERSION   = 0.1;

$BASE_PATH = '/www_share/intouch/files';
$BASE_DIR  = $BASE_PATH;

#
# private (non-exported) variables
#

my $_chunk_size = 256 * 1024;

my $_max_upload = (300 * 1024) * 1024; # 300MB

#
# private (non-exported) methods
#

#
# public class methods
#
sub repository_check {
  return (-d $BASE_DIR ? 1 : 0);
}

sub handler : method {
  my ($self, $r) = @_;

  my %in = map { Apache2::URI::unescape_url($_) } split /[=&;]/, $r->args;

  my $begin   = 0; # Boolean to determine if we've getting data
  my $length  = 0;
  my $chunks  = 0;
  my $chunk   = $_chunk_size;
  my $file_id = $in{'file_id'}; 
  my $replace = $in{'replace'}; 
  my $table;

  my $fh;

  my $upload_hook = sub {
    my ( $upload, $data, $data_len, $hook_data ) = @_;


    if ( !$begin ) {   # If this is the first set check the array length

      my $size = $ENV{CONTENT_LENGTH}; # $upload->size();
      my $file = $upload->upload_filename();
      my $type = $upload->upload_type();
      my $filename;

      # pull filename from end of $file string
      if ($file =~ m|[/\\:]+([^/\\:]+)$|) {
        $filename = $1;
      } else {
        $filename = $file;
      }

      # return unless we have a file
      return unless $filename;

      if ($replace) {
        HTML::Shark::D_UploadFile::replace_upload({name       => $filename,
                                           size       => $size,
                                           type       => $type,
                                           created_by => undef,
                                           file_id    => $file_id});
      } else {
        HTML::Shark::D_UploadFile::new_upload({name       => $filename,
                                       size       => $size,
                                       type       => $type,
                                       created_by => undef,
                                       file_id    => \$file_id});
      }
    }

    $begin = 1;
    if ($data) {
      $data_len = bytes::length($data);
    } else {
      $data_len = 0;
    }
    $length += $data_len;

    print $fh $data if $fh && $data;
    if ($length > $chunk) {
      $chunk += $_chunk_size;
      $chunks++;

      # update file status
      HTML::Shark::D_UploadFile::set_file_upload_status({file_id    => $file_id,
                                                 bytes_read => $length});
    }
  };

  # file_id should be a number
  $file_id =~ s/[^0-9]//g;

  # we must have a file_id
  if ($file_id) {
    my $req = Apache2::Request->new($r,
                                    UPLOAD_HOOK => $upload_hook,
                                    TEMP_DIR    => '/tmp',
    );

    $fh = new IO::File '>' . $BASE_DIR . '/' . $file_id;

    binmode($fh);

    $table = $req->param();

    my $upload = eval { $req->upload( 'userfile' ) };

    #if ( ref $@ and $@->isa("Apache2::Request::Error") ) {
    #  # ... handle Apache2::Request::Error object in $@
    #  $r->headers_out->set( Location => 'https://'
    #          . $r->construct_server
    #          . '/ksync/poll/data/upload/aborted' );
    #  return Apache2::Const::REDIRECT;
    #}

    # Finish up
    $fh->close;

    unless ($length) {
      # houston we have a problem

      # set status to error and remove file
      HTML::Shark::D_UploadFile::error_upload({file_id => $file_id});

      unlink $BASE_DIR . '/' . $file_id;
    } else {
      # grab post args and process
      my $owner       = $table->{'owner'};
      my $upload_type = $table->{'upload_type'} || '';
      my $folder_type = $table->{'folder_type'};
      my $cu_ids      = $table->{'selected_cu_def'};
      my $leas        = $table->{'selected_lea_def'};
      my $ccodes      = $table->{'selected_ccode_def'};
      my $date_id     = $table->{'survey_date_id'} || '0';
      my $month       = $table->{'month'} || '0';
      my $year        = $table->{'year'} || '0';
      my $path        = $table->{'path'} || '/intouch/file/display';
      my $public      = $table->{'public'} eq 'y' ? 1 : 0;
      my $file_type   = $table->{'file_type'} || '-';
      my $perm_arg    = $table->{'perm'} || '';
      my $cu_id       = $table->{'cu_id'} || '';
      my $ccode       = $table->{'ccode'} || '';

      # ugo, rw-rw-[r]--
      my $perm = ($perm_arg ? $perm_arg : 0600 | 0060 | ($public ? 04 : 00));

      HTML::Shark::D_UploadFile::complete_upload({file_id => $file_id,
                                          owner   => $owner,
                                          flag    => $file_type,
                                          perm    => $perm,
                                          size    => $length});

      # if we are XX (internal) set status to acknowledged (ack)
      if ($ccode eq 'XX') {
        HTML::Shark::D_UploadFile::file_status({file_id => $file_id,
                                        state   => 'ack'});
      }

      # extra processing
      # Set status so the progress window will close
      for ($upload_type) {
        # smaa_folder stuff
        /^smaa$/ && do {
          my $folder_id = HTML::Shark::D_UploadFile::check_folder_maa(
            {survey_date_id => $date_id, type => $folder_type});
          # create folder if needed
          unless($folder_id) {
            HTML::Shark::D_UploadFile::new_folder_maa({type           => $folder_type,
                                               perm           => $perm,
                                               owner          => $owner,
                                               group          => '',
                                               survey_date_id => $date_id,
                                               folder_public  => '',
                                               folder_id      => \$folder_id}); 
          }
          # add link
          HTML::Shark::D_UploadFile::folder_maa_link({folder_id => $folder_id,
                                              file_id   => $file_id}); 
          # add claiming unit links
          $cu_ids = $cu_id if $cu_ids eq '' && $cu_id ne '';
          if ($cu_ids) {
            $cu_ids =~ s/^scu=//;
            foreach my $cu_id (split('scu=', $cu_ids)) {
              if ($cu_id) {
                HTML::Shark::D_UploadFile::folder_maa_cu_link({folder_id => $folder_id,
                                                       cu_id     => $cu_id,
                                                       file_id   => $file_id}); 
              }
            }
          }
          last;
        };
        # corr_folder stuff
        /^corr$/ && do {
          my $folder_id = HTML::Shark::D_UploadFile::check_folder_corr(
            {date_id => $date_id, type => $folder_type,
             month => $month, year => $year});
          # create folder if needed
          unless($folder_id) {
            HTML::Shark::D_UploadFile::new_folder_corr({type           => $folder_type,
                                                perm           => $perm,
                                                owner          => $owner,
                                                group          => '',
                                                date_id        => $date_id,
                                                month          => $month,
                                                year           => $year,
                                                folder_public  => '',
                                                folder_id      => \$folder_id});
          }
          # add link
          HTML::Shark::D_UploadFile::folder_corr_link({folder_id => $folder_id,
                                               file_id   => $file_id});
          # add ccode links
          if ($ccodes) {
            $ccodes =~ s/^sccode=//;
            foreach my $ccode (split('sccode=', $ccodes)) {
              if ($ccode) {
                HTML::Shark::D_UploadFile::folder_corr_ccode_link(
                  {folder_id => $folder_id, ccode => $ccode,
                   file_id => $file_id});
              }
            }
          }
          last;
        };
        # shn_folder stuff
        /^shn$/ && do {
          my $folder_id = HTML::Shark::D_UploadFile::check_folder_shn(
            {date_id => $date_id, type => $folder_type,
             month => $month, year => $year});
          # create folder if needed
          unless($folder_id) {
            HTML::Shark::D_UploadFile::new_folder_shn({type           => $folder_type,
                                               perm           => $perm,
                                               owner          => $owner,
                                               group          => '',
                                               date_id        => $date_id,
                                               month          => $month,
                                               year           => $year,
                                               folder_public  => '',
                                               folder_id      => \$folder_id});
          }
          # add link
          HTML::Shark::D_UploadFile::folder_shn_link({folder_id => $folder_id,
                                              file_id   => $file_id});
          # add lea links
          if ($leas) {
            $leas =~ s/^slea=//;
            foreach my $lea (split('slea=', $leas)) {
              if ($lea) {
                HTML::Shark::D_UploadFile::folder_shn_lea_link({folder_id => $folder_id,
                                                        lea       => $lea,
                                                        file_id   => $file_id});
              }
            }
          }
          last;
        };
        # cmaa_folder stuff
        /^cmaa$/ && do {
          my $folder_id = HTML::Shark::D_UploadFile::check_folder_cmaa(
            {survey_date_id => $date_id, type => $folder_type,
             month => $month, year => $year});
          # create folder if needed
          unless($folder_id) {
            HTML::Shark::D_UploadFile::new_folder_cmaa({type           => $folder_type,
                                                perm           => $perm,
                                                owner          => $owner,
                                                group          => '',
                                                survey_date_id => $date_id,
                                                month          => $month,
                                                year           => $year,
                                                folder_public  => '',
                                                folder_id      => \$folder_id});
          }
          # add link
          HTML::Shark::D_UploadFile::folder_cmaa_link({folder_id => $folder_id,
                                               file_id   => $file_id});
  
          # add claiming unit links
          $cu_ids = $cu_id if $cu_ids eq '' && $cu_id ne '';
          if ($cu_ids) {
            $cu_ids =~ s/^scu=//;
            foreach my $cu_id (split('scu=', $cu_ids)) {
              if ($cu_id) {
                HTML::Shark::D_UploadFile::folder_cmaa_cu_link({folder_id => $folder_id,
                                                        cu_id     => $cu_id,
                                                        file_id   => $file_id});
              }
            }
          }
          last;
        };
      }
    
      # Send the user to the summary page
      $r->headers_out->set(
        Location => join('', 'https://', $r->construct_server, $path,
                         '?cfile_id=', $file_id)                   
      );
    }
  } else {
    # Send the user to the summary page
    $r->headers_out->set(
      Location => join('', 'https://', $r->construct_server,
                           '/intouch/file/error','?cfile_id=')
    );



  }
  return Apache2::Const::REDIRECT; 
}

1;
